<template>
  <Container class="mobile-form-modal">
    <div class="mobile-form-modal-inner">
      <div class="title">{{ $t("form.updateCert.title") }}</div>
      <a-form class="form" :model="formState" ref="formRef">
        <a-form-item
          :label="$t('form.updateCert.form_item_1_label')"
          name="fileList"
          :rules="[{ validator: checkFileList, trigger: 'blur' }]"
        >
          <UploadImg
            ref="uploadImg"
            @selectFile="selectFile"
            @removeFile="removeFile"
          ></UploadImg>
        </a-form-item>
      </a-form>
      <div class="footer-btn">
        <div class="footer-btn-inner">
          <a-button @click="goBack">{{ $t("btnText.cancel") }}</a-button>
          <a-button
            class="ensure-btn"
            :class="formIsValid ? '' : 'disabled'"
            type="primary"
            @click="continuePublish"
            >{{ $t("btnText.save") }}</a-button
          >
        </div>
      </div>
    </div>
  </Container>
</template>

<script setup lang="ts">
import { computed, getCurrentInstance, onMounted, ref } from "vue";
import { message } from "ant-design-vue";
import { useRouter } from "vue-router";
import { postCertificateAdd } from "../../api/profile";

const $t = getCurrentInstance()?.appContext.config.globalProperties.$t;

const router = useRouter();

const initForm = () => {};

const formIsValid = computed(() => {
  let flag = true;
  if (!formState.value.fileList.length) flag = false;
  return flag;
});

const selectFile = (file: File) => {
  formState.value.fileList.push(file);
};

const removeFile = (index: number) => {
  formState.value.fileList.splice(index, 1);
};

// Form Rules
const checkFileList = (_Rule: any, value: File[]) => {
  if (value.length == 0) {
    return Promise.reject($t("form.updateCert.form_item_1_rules_1"));
  } else {
    return Promise.resolve();
  }
};

// 发布
const formState = ref<{ fileList: File[] }>({
  fileList: [],
});

const formRef = ref();

const continuePublish = () => {
  if (!formIsValid.value) return;
  formRef.value.validate().then(() => {
    let successCount = 0;
    formState.value.fileList.forEach(async (file: File) => {
      let formData = new FormData();
      formData.append("file", file);
      await postCertificateAdd(formData);
      successCount += 1;
      if (successCount === formState.value.fileList.length) {
        message.success($t("message.upload_success"));
        goBack();
      }
    });
  });
};
const goBack = () => {
  router.go(-1);
};

onMounted(() => {
  initForm();
});
</script>
<style lang="less">
.mobile-form-modal {
  .wrap-container > .wrap-pl {
    padding-bottom: 0 !important;
  }
}
</style>
<style scoped lang="less">
@import url("./common.less");
:deep(.form) {
  .ant-form-item {
    .ant-row {
      flex-direction: column;
    }
  }
}
</style>
